//
//  ContactCustomerServiceViewController.m
//  CPICMobileServiceApp
//
//  Created by lizhiwei on 13-2-4.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "ContactCustomerServiceViewController.h"
#import "NSString+SBJson.h"
#import "Config.h"
#import "RCAlertViewUtil.h"
#import "UIImageView+WebCache.h"
#import "IFServiceEvaluation.h"

#define CallOutBtnWidth 355
#define CallOutBtnHeight 74
#define OnLineBtnWidth 200
#define OnLineBtnHeight 30

@interface ContactCustomerServiceViewController ()

@end

@implementation ContactCustomerServiceViewController
@synthesize progress;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"联系客服";
        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"CallCus_bg"]];
        //self.navigationController.navigationBarHidden = FALSE;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIImageView * BgImage = [[UIImageView alloc]init];
    BgImage.image = [UIImage imageNamed:@"CallCus_bg"];
    BgImage.frame = CGRectMake(0, 0, BgImage.image.size.width/2, BgImage.image.size.height/2);
    [self.view addSubview:BgImage];
    [BgImage release];
    
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"]) 
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"联系客服");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"联系客服");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"联系客服");
        
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }
	
    //添加“呼叫客服代表”按钮
    UIButton * CallOutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    CallOutBtn.frame = CGRectMake((self.view.frame.size.width-CallOutBtnWidth/2)/2, 220+44, CallOutBtnWidth/2, CallOutBtnHeight/2);
    [CallOutBtn setTitle:@"呼叫客服代表" forState:UIControlStateNormal];
    [CallOutBtn setBackgroundImage:[UIImage imageNamed:@"callBg355X74.png"] forState:UIControlStateNormal];
    [CallOutBtn addTarget:self action:@selector(ClickCallOutBtn1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:CallOutBtn];
    
    [self setTelephoneQryRequest];
    
    //添加“网上投保车险服务热线”按钮
    UIButton * OnLineBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    OnLineBtn.frame = CGRectMake((self.view.frame.size.width-OnLineBtnWidth)/2, 100, OnLineBtnWidth, OnLineBtnHeight);
    [OnLineBtn setTitle:@"网上投保车险服务热线" forState:UIControlStateNormal];
    [OnLineBtn addTarget:self action:@selector(ClickOnLineBtn) forControlEvents:UIControlEventTouchUpInside];
    //[self.view addSubview:OnLineBtn];
    
    [self setEvaluationRequest];
}

-(void) ClickCallOutBtn
{
    //呼叫客服代表
    /*UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:@"tel:95500"];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    [self.view addSubview:callWebview];*/
    if ([Flag isEqualToString:@"0"]) 
    {
        [self IFServiceEvaluation];
        Flag = @"1";
    }
    else 
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void) ClickCallOutBtn1
{
    //呼叫客服代表
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    if ([userdefault valueForKey:@"TELEPHONE"]) 
    {
        Telephone = [userdefault valueForKey:@"TELEPHONE"];
    }
    else 
    {
        Telephone = @"tel:95500";
    }
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:Telephone];
    callWebview.delegate = self;
    //[self IFServiceEvaluation];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    [self.view addSubview:callWebview];
    Flag = @"0";
}

-(void)setEvaluationRequest
{
    NSLog(@"==================");
    NSString *serviceid =@"40501";
    NSString *servicename =@"联系客服";
    IFServiceEvaluation *ifserviceevaluation =[[IFServiceEvaluation alloc]initView:serviceid withserviceName:servicename];
    [ifserviceevaluation setIfServiceEvaluationRequest];
    [ifserviceevaluation setHidden:YES];
    [self.view addSubview:ifserviceevaluation];
    [ifserviceevaluation release];
}
-(void) IFServiceEvaluation
{
    NSString *serviceid =@"40501";
     NSString *servicename =@"联系客服";
    NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    if ([myDefaults stringForKey:serviceid]) {
        NSString *strEvaluate=[myDefaults stringForKey:serviceid];
        if ([strEvaluate isEqualToString:@"1"]) {
            AddServiceEvaluationViewController *serviceevluation = [[AddServiceEvaluationViewController alloc]initView:serviceid withserviceName:servicename];
            [[AppDelegate app].unc pushViewController:serviceevluation animated:YES];
            [serviceevluation release];
        }
        else
        {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    else
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}


-(void) ClickOnLineBtn1
{
    //拨打网上投保车险服务热线
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:Telephone];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    [self.view addSubview:callWebview];
}

-(void)setTelephoneQryRequest//向太保移动平台发送电话号码类查询请求报文
{
    /*---------------------------
    服务类型定义如下所示:
    自助报案电话，ServerType=PH_1001、
    联系客服电话，ServerType=PH_1002、
    电话投保电话:ServerType=PH_1003、
    救援服务电话，ServerType=PH_1004、
    代驾服务电话，ServerType=PH_1005
    -----------------------------*/
    NSString * useraccount = @"admin";
//    NSString *strRequestCode=@"RequestCode=40501";
    NSString *strRequestData=[NSString stringWithFormat:@"{\"ServerType\":\"PH_1002\",\"UserAccount\":\"%@\"}",useraccount];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestData];
//    NSLog(@"++++++++++++++%@",strUrl);
//    strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    
//    NSURL *myurl = [NSURL URLWithString:strUrl];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"URL:%@",myurl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"40501" forKey:@"RequestCode"];
    [request setPostValue:strRequestData forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress)
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"加载中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSMutableDictionary *jsonoSubObj = [dictResponse objectForKey:@"head"];
    NSString * ss = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"success"]];
    if ([ss isEqualToString:@"1"])
    {
        NSString *servicePhone = [[NSString alloc] initWithFormat:@"%@",[dictResponse objectForKey:@"servicePhone"]];
        Telephone = [[NSString alloc] initWithFormat:@"tel:%@",servicePhone];
        NSLog(@"-----------%@",Telephone);
        NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
        [userdefault setObject:Telephone forKey:@"TELEPHONE"];
    }
    else
    {
        [self justShowMessage:@"获取号码失败！" title:@"提示"];
    }
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败！" title:@"提示"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [progress release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
